//
//  MKRefreshLeftView.m
//  Category
//
//  Created by Burn on 2020/1/8.
//  Copyright © 2020 menksoft. All rights reserved.
//

#import "MKRefreshLeftView.h"
#import "UIView+Extension.h"
#import "RefreshConst.h"
@interface MKRefreshLeftView ()

@property(weak,nonatomic) id target;

@property(assign,nonatomic) SEL action;

@property(strong,nonatomic) UILabel *leftTitle;

@property(assign,nonatomic) BOOL panState;

@property(assign,nonatomic) CGFloat offsetx;

@end


@implementation MKRefreshLeftView

+ (instancetype)leftWithRefreshingTarget:(id)target refreshingAction:(SEL)action{
    
    return [[[MKRefreshLeftView alloc]init] leftWithRefreshingTarget:target refreshingAction:action];
}

- (instancetype)leftWithRefreshingTarget:(id)target refreshingAction:(SEL)action{
    MKRefreshLeftView *leftView = [[MKRefreshLeftView alloc]init];
    leftView.leftTitle = [[UILabel alloc]init];
    leftView.leftTitle.backgroundColor = [UIColor redColor];
    leftView.target = target;
    leftView.action = action;
    [leftView addSubview:self.leftTitle];
    leftView.leftTitle.text = @"footer";
    
    leftView.backgroundColor = [UIColor orangeColor];
    return leftView;
}

- (void)endRefreshing{
    [UIView animateWithDuration:.25 animations:^{
        self.scrollView.contentInset = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0, self.scrollView.contentInset.bottom, self.scrollView.contentInset.right);
    }];
    self.state = RefreshIdle;
    self.panState = NO;
}

- (void)didMoveToSuperview{
    UICollectionView *collectionView = (UICollectionView *)self.scrollView;
    collectionView.alwaysBounceHorizontal = YES;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.frame = CGRectMake(-MKRefreshContentInsetSpacing, 0, self.height, self.scrollView.height);
    self.leftTitle.frame = self.bounds;
}

- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{
    [super scrollViewContentOffsetDidChange:change];
    
    if (self.state == RefreshRefreshing) {
        return;
    }
    
    if (self.panState && self.state == RefreshIdle) {
        if (self.offsetx <= -MKRefreshContentInsetSpacing) {
            self.state = RefreshRefreshing;
            [UIView animateWithDuration:.25 animations:^{
                self.scrollView.contentInset = UIEdgeInsetsMake(self.scrollView.contentInset.top, MKRefreshContentInsetSpacing, self.scrollView.contentInset.bottom, self.scrollView.contentInset.right);
            }];
            [self.target performSelector:self.action];
        }
    }
}

- (void)scrollViewContentSizeDidChange:(NSDictionary *)change{
    [super scrollViewContentSizeDidChange:change];
    
}

- (void)scrollViewPanStateDidChange:(NSDictionary *)change{
    [super scrollViewPanStateDidChange:change];
    self.panState = [change[@"new"] integerValue] == 3;
    self.offsetx = self.scrollView.contentOffset.x;
}













@end
